/**
* OpenSocial gadget contents loader
* 2010 codsworks
*/


var osgcl = {};


osgcl.gadgetRootUrl = '';


osgcl.init = function() {
    if (osgcl.gadgetRootUrl == '') {
        alert('[osgcl] Required application root url.');
        return false;
    }
    
    osgcl.viewName = gadgets.views.getCurrentView().getName();
    osgcl.loadContents();
};


osgcl.loadContents = function() {
    osgcl.loadCss(osgcl.viewName + '.css');
    var url = osgcl.gadgetRootUrl + '/' + osgcl.viewName + '.html';
    osgcl.requestGetText(url, function(html) {
        html = html.replace(/src="([^:]+?)"/g, 'src="' + osgcl.gadgetRootUrl + '/$1"');
        $('body').append('<div id="osgcl_content_wrapper"></div>');
        $('#osgcl_content_wrapper').html(html);
        osgcl.loadJs(osgcl.viewName + '.js');
    });
};


osgcl.loadCss = function(path) {
    var url = osgcl.gadgetRootUrl + '/' + path;
    $('head').append('<link rel="stylesheet" type="text/css" href="' + url + '">');
};


osgcl.loadJs = function(path) {
    var url = osgcl.gadgetRootUrl + '/' + path;
    $('body').append('<script type="text/javascript" src="' + url + '"></script>');
};


osgcl.requestGetText = function(url, callback) {
    var params = {};

    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    params[gadgets.io.RequestParameters.CONTENT_TYPE]  = gadgets.io.ContentType.TEXT;
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.NONE;
        
    gadgets.io.makeRequest(url, function(res) {
        callback(res.data);
    }, params);
};


gadgets.util.registerOnLoadHandler(osgcl.init);
